#ifndef channel_h
#define channel_h

#define CCHANENEL_CONNECT_ADDR_MAXLEN 250
#include "stdafx.h"

class CMsgbusChannel
{
public:
    CMsgbusChannel(void) { }
    virtual ~CMsgbusChannel(void) { }

    HRESULT CreateCChannel(IBase* pSocket)
    {
        HRESULT hr = S_OK;
        rc_error(pSocket != NULL, E_FAIL);

        hr = pSocket->QueryInterface(IID_ITcpSocket, (void**)&m_pISocket);
        rc_error(hr == S_OK, E_FAIL);

        hr = m_pISocket->CreateSock();
        rc_error(hr == S_OK, E_FAIL);

        return hr;
    }

    HRESULT ConnectChannel(LPCSTR addr, int len, crtid event)
    {
        rc_error(addr != NULL, E_FAIL);
        rc_error(len != 0, E_FAIL);

        CharArrayPtr item;
        item.dispose();
        item = ALLOC_NEW char[CCHANENEL_CONNECT_ADDR_MAXLEN + 1]();
        rc_error(item.m_p != NULL, E_FAIL);
        s_strcpy(item, CCHANENEL_CONNECT_ADDR_MAXLEN, addr);

        char* port = NULL;
        char* ip = NULL;

        ip = s_strtok(item, ":", &port);
        rc_error(ip != NULL, E_FAIL);
        rc_error(port != 0, E_FAIL);
        rc_error(m_pISocket != NULL, E_FAIL);

        return m_pISocket->ConnectIo(ip, atoi(port), event, 5);
    }

    HRESULT CloseChannel()
    {
        rc_error(m_pISocket != NULL, E_FAIL);

        HRESULT hr = S_OK;

        hr = m_pISocket->CloseSock();
        rc_error(hr == S_OK, E_FAIL);

        m_pISocket.dispose();

        return S_OK;
    }

private:
    _lComPtr<ITcpSocket> m_pISocket;
};

#endif
